/**
 * 详情对话框
 */
var PictureVideoInfoDlg = {
    data: {
        pictureName: "",
        pictureUrl: "",
        videoName: "",
        videoUrl: "",
        uploadTime: ""
    }
};

layui.use(['form', 'admin', 'ax','upload', 'layedit'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var upload = layui.upload;
    var layedit = layui.layedit;
    var _index=1;
    var newPathList=[];
    //让当前iframe弹层高度适应
    admin.iframeAuto();


    var imgs = "";



    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/pictureVideo/detail");
    var result = ajax.start();
    /**
     * 循环遍历图片
     */
    if (result.data.pictureUrl != null && result.data.pictureUrl != '') {
        var html = "";
        imgs = result.data.pictureUrl.split(",");
        for (var i = 0; i < imgs.length; i++) {
            if(imgs[i]){
                html = html + '<div id="" class="file-iteme file-iteme-'+i+'">' +
                    '<div class="handle"></div>' +
                    '<img style="width: 30%" src="' + imgs[i] + '" alt="' + imgs[i] + '" class="layui-upload-img">' +
                    '<div class="info">' + '<span class="layui-icon layui-icon-delete shanchu" data-class="file-iteme-'+i+'" data-value="' +imgs[i]+ '"></span>' + '</div>' +
                    '<div><input type="number" name="changeIndex" class="changeIndex" data-index="'+_index+'" data-key="'+_index+'" style="max-width: 70px;margin: 40px auto;" placeholder="请输入对应图片的排序序号"/></div>' +
                    '</div>';
                _index++;
            }
        }

        $("#pictureUrl").val(imgs.join(","));

        $('#demo2').append(html);

        $(".shanchu").click(function (e) {
            var img=$(this).attr('data-value')
            var part='.'+$(this).attr('data-class')
            shanchu(img,part)
        })
        $('.changeIndex').each(function (e){
            $(this).val($(this).attr('data-index'))
        })
    }

    $(document).on("change", ".changeIndex", function (event) {
        //现在输入的序号，
        var val=$(this).val();
        console.log(val)
        //原来的序号的序号，
        var valIndex=$(this).attr('data-index');
        console.log(valIndex)
        if(val>$('.changeIndex').length){
            $(this).val($('.changeIndex').length)
        }
        if(val<1){
            $(this).val(1);
        }
        //吧输入的新序号和对应位置序号调换
        $('.changeIndex').each(function (e){
            //如果输入的值和原来的序号对应
            if($(this).attr('data-index')==val){
                $(this).val(valIndex);//对应的序号框改变值
                $(this).attr('data-index',valIndex);//原来的序号的序号也需要改变
                changeIndexPath();
            }
            //
            // if(e+1==val){
            //
            // }
        })
        //改变对应的原来的序号的序号
        $(this).attr('data-index',val);
    });
    var changeIndexPath =function () {
        //获取所有的图片地址；
        var allPath= $("#pictureUrl").val().split(',');


        //$('.changeIndex')的下标对应的图片地址的下标；
        $("input[name='changeIndex']").each(function (e){
            var newIndex=parseInt($(this).val())-1;
            var oldPath=parseInt($(this).attr('data-key'))-1;//最初的排列标示
            if(oldPath!=oldPath.length-1){
                newPathList[newIndex]=allPath[oldPath]
            }

        });
        var new_path='';
        newPathList.forEach(function (item,index) {
            new_path+=item+",";
        })
        console.log(newPathList);
        console.log(new_path);
        $("#pictureUrl").val(new_path);
    };


    /**
     * 删除图文
     */
    window.shanchu = function(i,b){
        $.ajax({
            "url": Feng.ctxPath + "/pictureVideo/updateImg?img=" + i + ",",
            "type": "POST",
            //"date":{"img":i} ,
            "dataType": "JSON",
            "success": coolBack
        });
        <!--获取回调函数-->
        function coolBack() {
            Feng.success("删除数据成功！");
            //window.location.reload();

            $(b).remove()
            var pathImg=$("#pictureUrl").val().split(',');
            var newPath='';
            for (var j=0;j<pathImg.length;j++){
                if(pathImg[j]&& pathImg[j]!=i){
                    newPath+=pathImg[j]+","
                }
            }
            $("#pictureUrl").val(newPath);

        }
    }




    /**
     * 循环遍历视频
     */
    if (result.data.videoUrl != null && result.data.videoUrl != '') {
        var html = "";
        var videoUrlimgs = result.data.videoUrl.split(",");
        for (var i = 0; i < videoUrlimgs.length; i++) {
            if(videoUrlimgs[i]){
                html = html + '<div id="" class="file-iteme">' +
                    '<div class="handle"></div>' +
                    '<video style="width: 60%; height: 50%;" controls preload="auto">' +
                    '<source src="' + videoUrlimgs[i] + '" type="video/mp4" controls autoplay />' +
                    '</video>' +
                    '<div class="info">' + '<span class="layui-icon layui-icon-delete" onclick="videoUrlimgsshanchu(\'' + videoUrlimgs[i] + '\')"></span>' + '</div>' +
                    '</div>';
            }
        }

        $("#videoUrl").val(videoUrlimgs.join(","));

        $('#demo3').append(html);
    }






    form.val('pictureVideoForm', result.data);

    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/pictureVideo/editItem", function (data) {
            Feng.success("更新成功！");
            window.location.href = Feng.ctxPath + '/goods'
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/goods'
    });


    // 删除图片
    $(document).on("click", "#deleteBillpic", function (event) {
        $("#demo2").html("");
        $("#pictureUrl").val("");
    });



    /**
     * 循环的次数
     */
    var cycle = 0;
    var rescycle = 0;
    /**
     * 上传图文图片
     */
    upload.render({
        elem: '#bill_pic'
        , url: Feng.ctxPath + '/pictureVideo/picture'
        , multiple: true
        , before: function (obj) {
            obj.preview(function (index, file, result) {
                cycle ++;

            });
        }
        , done: function (res) {
            rescycle++;
            layer.msg(res.message);
            if(rescycle == cycle){
                $("#pictureUrl").val($("#pictureUrl").val()+res.data);
                res.data=  res.data.split(',')
                for(var i =0;i<res.data.length;i++){
                    if(res.data[i]){
                        $('#demo2').append(
                            '<div id="" class="file-iteme-l-'+i+'">' +
                            '<img style="width: 30%" src="' + res.data[i] + '"  class="layui-upload-img">' +
                            '<div class="handle"><span class="layui-icon layui-icon-delete shanchuSh" data-class="file-iteme-l-'+i+'" data-value="' +res.data[i]+ '"></span></div>' +
                            '<div><input type="number" name="changeIndex" class="changeIndex" data-index="'+_index+'" data-key="'+_index+'" style="max-width: 70px;margin: 40px auto;" placeholder="请输入对应图片的排序序号"/></div>' +
                            '</div>'
                        )
                        _index++;
                        $('.changeIndex').each(function (e){
                            $(this).val($(this).attr('data-index'))
                        })
                    }
                }

                $(".shanchuSh").click(function (e) {
                    var img=$(this).attr('data-value')
                    var part='.'+$(this).attr('data-class')
                    shanchuSh(img,part)
                })

            }

        },
        error: function (res) {
            layer.msg(res.message);
        }
    });


//删除
    window.shanchuSh = function(e,b){

        $(b).remove()
        var pathImg=$("#pictureUrl").val().split(',');
        var newPath='';
        for (var j=0;j<pathImg.length;j++){
            if(pathImg[j]&& pathImg[j]!=e){
                newPath+=pathImg[j]+","
            }
        }
        $("#pictureUrl").val(newPath);
    }



    /**
     * 上传视频文件
     */
    upload.render({
        elem: '#bill_pic3'
        , url: Feng.ctxPath + '/pictureVideo/video'
        , multiple: true
        , accept: 'file'
        , before: function (obj) {
            obj.preview(function (index, file, result) {
                $('#demo3').append(
                    '<div id="" class="file-iteme">' +
                    '<img style="width: 30%" src="' + result + '" alt="' + file.name + '" class="layui-upload-img">' +
                    '<div class="handle"><span class="layui-icon layui-icon-delete"></span></div>' +
                    '</div>'
                )
            });
        }
        , done: function (res) {
            layer.msg(res.message);
            if(rescycle == cycle){
                $("#videoUrl").val(res.data);
            }

        },
        error: function (res) {
            layer.msg(res.message);
        }
    });












});
